from django.shortcuts import render,redirect
from django.views.generic.base import reverse
from django.contrib.auth import login  #这里少了
from AgentLogin import AgentLogin
from django.views.generic import View
from django.conf import settings
from django.http import JsonResponse,HttpResponseForbidden
from django.http import HttpResponse
from .models import QQAuthUser
from .utils import generate_secret_openid,check_secret_openid
import re
from django_redis import get_redis_connection
from  userapp.models import Users

# Create your views here.
class QQLoginURLView(View):
    def get(self,request):
        '''
        获取qq扫码登录连接的一个地址
        '''
        qq_url=AgentLogin.qq_url(settings.QQ_CLIENT_ID,settings.QQ_REDIRECT_URI)
        return  JsonResponse({'code':200,'errormsg':'OK','login_url':qq_url})
class QQAuthUserView(View):
    def get(self,request):
        code=request.GET.get('code','')
        #校验参数
        if not code :
            return HttpResponseForbidden('缺少必要参数')
        nickname,openid=AgentLogin.qq(settings.QQ_CLIENT_ID,settings.QQ_APP_KEY,settings.QQ_REDIRECT_URI,code)
        #通过openid判断qq用户是否绑定项目用户
        try:
            qq_user=QQAuthUser.objects.get(openid=openid)
        except QQAuthUser.DoesNotExist:
            #qq用户没有绑定项目用户
            #加密openid数据
            sec_openid=generate_secret_openid(openid)
            #传递加密数据给用户绑定页面
            return render(request,'oauth/oauth_user.html',{'sec_openid':sec_openid})

        else:
            #获取关联的项目用户对相象
            mg_user=qq_user.user
            #状态保持
            login(request,mg_user)
            #响应结果
        return redirect(reverse('newsapp:index'))
    def post(self,request):
        """
        将当前访问的qq用户绑定醒目用户
        """
        #接收参数
        sec_openid=request.POST.get('sec_openid','')
        sms_code=request.POST.get('msgcode','')
        phone=request.POST.get('phone','')
        password=request.POST.get('password','')
        #校验参数
          #非空校验
        if not all([sec_openid,sms_code,phone,password]):
            return HttpResponseForbidden('缺少必要参数')
          #格式校验
        if not re.match(r'^1[35789]\d{9}',phone):
            return HttpResponseForbidden('请输入正确手机号密码')
        if not re.match(r'[a-zA-Z0-9]{3,8}',password):
            return HttpResponseForbidden('请输入正确密码')
          #一致性校验
        redis_coon=get_redis_connection('verify_code')
        sms_code_server=redis_coon.get('img_%s'%phone).decode('utf-8')
        if sms_code_server is None:
            return render(request, 'oauth/oauth_user.html', {'sms_code_errmsg': '短信验证码不能为空'})
        if sms_code_server!=sms_code:
            return render(request,'oauth/oauth_user.html',{'sms_code_errmsg':'短信验证码错误'})
        #绑定用户
        #判断当前qq用户是否正常
        open_id=check_secret_openid(sec_openid)
        if not open_id:
            return render(request, 'oauth/oauth_user.html', {'openid_errmsg': 'openid已经失效'})
        try:
            user=Users.objects.get(phone=phone)
        except Users.DoesNotExist:
            user=Users.objects.create_user(username=phone,password=password)
        else:
            #判断用户密码是否正确
            if user.check_password(password):
                return render(request,'oauth/oauth_user.html',{'qq_login_errmsg':'密码错误'})
        #绑定用户
        QQAuthUser.objects.create(user=user,openid=open_id)
        #状态保持
        login(request,user)
        #响应结果
        return redirect(reverse('newsapp:index'))